from flask import Blueprint, render_template, request
from flask_login import current_user
from sqlalchemy import desc, text, func

from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import WalmartMsgResult
from applications.schemas import WalmartMsgResultOutSchema

walmart_record = Blueprint('walmartRecord', __name__, url_prefix='/walmart/record')


# 用户管理
@walmart_record.get('/')
@authorize("walmart:record:main")
def main():
    return render_template('walmart/record/main.html')


@walmart_record.get('/data')
@authorize("walmart:record:main")
def data():
    batch_no = str_escape(request.args.get('batch_no'))
    # 查询参数构造
    mf = ModelFilter()

    if batch_no:
        mf.exact(field_name="batch_no", value=batch_no)
    create_id = current_user.id
    # 非超级管理员只能查询当前用户创建的账号
    if create_id != 1:
        mf.exact(field_name="create_id", value=create_id)

    record = db.session.query(func.count(WalmartMsgResult.id).label('total'),
                              func.sum(text("IF( msg_result->'$.code' = 0, 1, 0)")).label('zhong_qian_num'),
                              WalmartMsgResult.batch_no,
                              WalmartMsgResult.create_at
                              ) \
        .filter(mf.get_filter(WalmartMsgResult)) \
        .group_by(WalmartMsgResult.batch_no).order_by(desc(WalmartMsgResult.batch_no)).layui_paginate()
    # 返回api
    return table_api(data=model_to_dicts(schema=WalmartMsgResultOutSchema, data=record.items), count=record.total)


@walmart_record.get('/detailPage/<string:batch_no>')
@authorize("walmart:record:main")
def detail_page(batch_no):
    return render_template('walmart/record/table.html', batch_no=batch_no)


#   分页查询
@walmart_record.get('/detailData')
@authorize("walmart:record:main")
def detail_data():
    # 获取请求参数
    name = str_escape(request.args.get("name"))
    phone = str_escape(request.args.get('phone'))
    batch_no = str_escape(request.args.get('batch_no'))
    flag = str_escape(request.args.get('flag'))
    # 查询参数构造
    mf = ModelFilter()
    if name:
        mf.contains(field_name="name", value=name)
    if phone:
        mf.contains(field_name="phone", value=phone)
    if batch_no:
        mf.exact(field_name="batch_no", value=batch_no)
    if not flag:
        flag = 0
    else:
        flag = int(flag)

    create_id = current_user.id
    # 非超级管理员只能查询当前用户创建的账号
    if create_id != 1:
        mf.exact(field_name="create_id", value=create_id)
    # orm查询
    # 使用分页获取data需要.items
    record = WalmartMsgResult.query.filter(mf.get_filter(WalmartMsgResult),
                                           text(" msg_result->'$.code' = {}".format(flag))) \
        .order_by(desc(WalmartMsgResult.id)).layui_paginate()
    count = record.total
    # 返回api
    return table_api(data=model_to_dicts(schema=WalmartMsgResultOutSchema, data=record.items), count=count)

# # 用户增加
# @walmart_record.get('/add')
# @authorize("walmart:record:add", log=True)
# def add():
#     return render_template('walmart/record/add.html')
#
# #
# @walmart_record.post('/save')
# @authorize("walmart:record:add", log=True)
# def save():
#     req_json = request.json
#     name = str_escape(req_json.get("name"))
#     phone = str_escape(req_json.get('phone'))
#
#     if not name or not phone:
#         return fail_api(msg="账号信息不得为空")
#
#     user_data = WalmartUser.query.filter_by(phone=phone).first()
#     if user_data is not None:
#         return fail_api(msg="该账号已存在")
#
#     create_id = current_user.id
#     user = WalmartUser(name=name, phone=phone, create_id=create_id)
#
#     db.session.add(user)
#     db.session.commit()
#     return success_api(msg="增加成功")

#
# # 删除用户
# @walmart_record.delete('/remove/<int:id>')
# @authorize("walmart:record:remove", log=True)
# def delete(id):
#     res = WalmartUser.query.filter_by(id=id).delete()
#     if not res:
#         return fail_api(msg="删除失败")
#     db.session.commit()
#     return success_api(msg="删除成功")
#
#
# # 批量删除
# @walmart_record.delete('/batchRemove')
# @authorize("walmart:record:remove", log=True)
# def batch_remove():
#     ids = request.form.getlist('ids[]')
#     for id in ids:
#         res = WalmartUser.query.filter_by(id=id).delete()
#         if not res:
#             return fail_api(msg="批量删除失败")
#     db.session.commit()
#     return success_api(msg="批量删除成功")
